const express = require('express');
const path = require('path');
const cors = require('cors')
const {expressjwt: expressJWT} = require('express-jwt')
const config = require('./config')
const usersRouter = require('./routes/users');
const userInfoRouter = require('./routes/userinfo')
const departmentsRouter = require('./routes/departments')
const roleRouter = require('./routes/role')
const employeeRouter = require('./routes/employee')
const joi = require('joi')

const app = express();
// const obj = {name:'zs'}
// obj.__proto__= {
//     age:18
// }
// console.log(obj.age)
// 中间件函数
app.use(cors())
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use('/public',express.static(path.join(__dirname, 'public')));
app.use(expressJWT({secret: config.jwtSecretKey, algorithms: ["HS256"]}).unless({path: [/^\/api\//]}))
// 登录路由
app.use('/api', usersRouter);

// 获取用户信息路由
app.use('/my', userInfoRouter)

// 获取部门信息路由
app.use(departmentsRouter)

// 获取角色路由
app.use(roleRouter)

// 获取员工路由
app.use(employeeRouter)

// 错误级别中间件
app.use((err, req, res, next) => {
    if (err.name === 'UnauthorizedError') {
        return res.send({
            status: 401,
            message: 'token无效!'
        })
    }
    // Joi 参数校验失败
    if (err instanceof joi.ValidationError) {
        return res.send({
            status: 1,
            message: err.message
        })
    }
    // 未知错误
    return res.send({
        status: 3,
        message: err.message
    })
})

module.exports = app;
